import { Http, Headers, Response,Jsonp, RequestOptions, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/toPromise';

import { Injectable } from '@angular/core';

import { User } from './user';
import { SERVER } from '../../app.config';

@Injectable()
export class UserService {
    constructor(private http: Http){

    }

    private user: User;

    getUsers(): Promise<User[]> {
        return this.http.get(SERVER.USER)
        .toPromise()
        .then(response => response.json() as User[])
        .catch(this.handleError);
    }

    getUser(user_id: number) {
        return this.getUsers()
            .then(users => users.find(user => user.user_id ===user_id ));
    }

    private handleError(error: any): Promise<any> {
        console.error('错误：', error);

        return Promise.reject(error.message || error);
    }

    //登录
    login(username: string, password: string): Promise<User> {
        let user = new User();
        user.login_username = username;
        user.login_password = password;

        let headers = new Headers({
            'Content-Type': 'application/json'
        });

        return this.http.post(SERVER.USER + '/login', JSON.stringify(user), {headers : headers})
            .toPromise()
            .then(this.extractData)
            .catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body || { };
    }


    //修改密码
    changepassword(username: string, password: string, passwordnew: string): Promise<User> {
        let user = new User();
        user.login_username = username;
        user.login_password = password;
        user.login_password_new = passwordnew;

        let headers = new Headers({
            'Content-Type': 'application/json'
        });

        return this.http.post(SERVER.USER + '/changepassword', JSON.stringify(user), {headers : headers})
            .toPromise()
            .then(this.extractData)
            .catch(this.handleError);
    }

    //添加
    private post(user: User): Promise<User> {
        let headers = new Headers({
            'Content-type': 'application/json'});

        return this.http.post(SERVER.USER, JSON.stringify(user), {headers: headers})
        .toPromise()
        // .then(res => res.json())
        .catch(this.handleError);
    }

    //更新
    private put(user: User): Promise<User> {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let url = `${SERVER.USER}` + '/'+ user.user_id;

        return this.http.put(url, JSON.stringify(user), {headers: headers})
                   .toPromise()
                   .then(() => user)
                   .catch(this.handleError);
    }

    //删除
    delete(user: User): Promise<Response> {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let url = `${SERVER.USER}/${user.user_id}`;

        return this.http
                   .delete(url, { headers: headers})
                   .toPromise()
                   .catch(this.handleError);
    }

    //保存
    save(user: User): Promise<User> {
        if (user.user_id) {
            return this.put(user)
        }
        return this.post(user);
    }

    //重置密码
    resetPassword(user: User): Promise<User> {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let url = `${SERVER.USER}` + '/resetpassword';

        return this.http
                   .post(url, JSON.stringify(user), { headers: headers})
                   .toPromise()
                   .then(res => res.json())
                   .catch(this.handleError);
    }
}
